package com.tjs.netty.medium;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.tjs.netty.param.Response;
import com.tjs.netty.param.ServerRequest;

public class Media {

	// key 是 类完整路径.方法名 类似 com.tjs.user.controller.UserController
	public static final Map<String, BeanMethod> beanMap = new HashMap<>();

	private static Media m = null;

	public static Media newInstance() {
		if (m == null) {
			synchronized (Media.class) {
				if (m == null) {
					m = new Media();
				}
			}
		}
		return m;
	}

	// 反射处理业务
	public Response process(ServerRequest request) {
		Response response = null;
		try {
			String command = request.getCommand();
			
			BeanMethod beanMethod = beanMap.get(command);
			if (beanMethod == null) {
				return null;
			}
			
			Object bean = beanMethod.getBean();

			Method m = beanMethod.getMethod();
			
			//TODO 以后这里处理要准确，因为现在只处理一个参数的方法，如果有两个参数就报异常
			Class<?> paramType  = null ;
			if (m.getParameterTypes().length >= 1) {
				paramType = m.getParameterTypes()[0];
			}

			Object content = request.getContent();
			Object args = JSONObject.parseObject(JSONObject.toJSONString(content), paramType);
			Object result = m.invoke(bean, args);
			response = new Response(request.getId(), result);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		
		return response;
	}

}
